package edu.johnpank.libassistant.controllers

import edu.johnpank.libassistant.entity.User
import edu.johnpank.libassistant.enums.Role
import edu.johnpank.libassistant.security.PersonDetails
import edu.johnpank.libassistant.services.UserService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.context.event.ApplicationReadyEvent
import org.springframework.context.annotation.ComponentScan
import org.springframework.context.event.EventListener
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.stereotype.Controller
import org.springframework.ui.Model
import org.springframework.web.bind.annotation.GetMapping
import java.util.GregorianCalendar

@Controller
@ComponentScan
class MainController(
    @Autowired
    val userService: UserService
) {
    // if db is empty (first start application) then add default admin
    @EventListener(ApplicationReadyEvent::class)
    fun doSomethingAfterStartup() {
        if (userService.getAllUser().isEmpty()){
            println("db is empty, creating default admin")
            val defAdmin:User = User()
            defAdmin.email = "admin@admin.edu"
            defAdmin.firstName = "admin"
            defAdmin.isConfirmed = true
            defAdmin.roles.add(Role.ROLE_ADMIN)
            defAdmin.roles.add(Role.ROLE_LIBRARIAN)
            defAdmin.lastName = "admin"
            defAdmin.login = "admin"
            defAdmin.password = "\$2a\$12\$/ohuMD1nCywqX7E9m1kQVeAX5S1Bv9ASE5f3734hsszS.RWQgWd2i"
            defAdmin.regDate = GregorianCalendar().timeInMillis

            userService.addUser(defAdmin)
        }
    }

    @GetMapping("/main")
    fun showMainPage(model: Model): String {

        //get user info from user thread
//        val authentication = SecurityContextHolder.getContext().authentication
//        val userDetails: PersonDetails = authentication.principal as PersonDetails
//        println(userDetails.getUser().login)

        return "main_page"
    }

    @GetMapping("about")
    fun showAboutPage(model: Model): String {

        return "about_page"
    }

}